from datetime import datetime, timedelta
from typing import Annotated, Optional

from fastapi import APIRouter, Depends, BackgroundTasks, Request, Body

from sanren.utils import get_current_active_user, Helper
from application.http import schemas
from application.http.models import OemModel, CodeModel
from application.http.schemas import ApiSchemas
from application.config import appSettings


router = APIRouter(prefix='/brand/v2', tags=['Brand'])
module_name = '品牌商模块 - v2模板'


@router.get('/verifys', response_model=schemas.BaseApiListOut)
async def get_verifies(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    page_params: schemas.PageParams = Depends(),
    code: Optional[str] = None,
):
    """
        品牌商 v2防伪信息
    """

    objs = OemModel.VerifyTemplate.with_('company')

    if code:
        objs = objs.where('code', code)

    objs = objs.order_by('id', 'desc').paginate(page_params.pageSize, page_params.page)

    return objs.serialize()


@router.get('/verifys/{code}', response_model=schemas.BaseApiOut)
async def get_verify(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    code: Optional[str] = None,
):

    obj = OemModel.VerifyTemplate.with_('company').where('code', code).first()
    if obj is None:
        return schemas.BaseApiOut(code=1, message='找不到此商户的v2防伪文案')

    return {'data': obj.serialize()}


@router.post('/verifys', response_model=schemas.BaseApiOut)
async def add_verify(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    post: dict = Body(...),
):
    obj = OemModel.VerifyTemplate.where('code', post.get('code')).first()
    if obj is not None:
        return schemas.BaseApiOut(code=1, message='此商户已经存在防伪文字信息,不能再添加防伪文案')

    try:
        OemModel.VerifyTemplate.create(
            code=post.get('code'),
            small_template=post.get('small_template'),
            ewm_template=post.get('ewm_template'),
            status=1,
        )
        return {'message': '操作成功'}
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')


@router.put('/verifys/{id}', response_model=schemas.BaseApiOut)
async def edit_verify(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    id: int,
    post: dict = Body(...),
):
    obj = OemModel.VerifyTemplate.find(id)
    if obj is None:
        return schemas.BaseApiOut(code=1, message='找不到此商户的v2防伪文案')

    try:
        obj.small_template = post.get('small_template')
        obj.ewm_template = post.get('ewm_template')
        obj.save()

        return {'message': '操作成功'}
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')


@router.get('/templates', response_model=schemas.BaseApiListOut)
async def get_templates(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    page_params: schemas.PageParams = Depends(),
    code: Optional[str] = None,
    is_default: Optional[int | str] = None,
    keyword: Optional[str] = None,
):
    """
        品牌商 v2模板列表
    """

    objs = OemModel.V2Oem.with_('company')

    if code:
        objs = objs.where('code', code)
    if is_default:
        objs = objs.where('is_default', is_default)
    if keyword:
        objs = objs.where(lambda query: query.where('domain', 'like', f'%{keyword}%').or_where('code', 'like', f'%{keyword}%'))

    objs = objs.order_by('id', 'desc').paginate(page_params.pageSize, page_params.page)

    return objs.serialize()


@router.post('/templates', response_model=schemas.BaseApiOut)
async def add_template(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    post: dict = Body(...),
):
    company = OemModel.Company.where('code', post.get('code')).first()
    if company is not None:
        return schemas.BaseApiOut(code=1, message='找不到此商户信息')

    domain = post.get('domain')
    if domain is None or domain == '':
        return schemas.BaseApiOut(code=1, message='域名不能为空')
    oem = OemModel.V2Oem.where('domain', domain).first()
    if oem is not None:
        return schemas.BaseApiOut(code=1, message='此域名已经存在,不能再添加')

    try:
        obj = OemModel.V2Oem.create(
            code=post.get('code'),
            domain=post.get('domain'),
            is_default=post.get('is_default'),
            small_template=post.get('small_template'),
            ewm_template=post.get('ewm_template'),
            status=post.get('status'),
        )

        if post.get('is_default') == 1:
            OemModel.V2Oem.where('id', '!=', obj.fresh().id).where('is_default', 1).update({'is_default': 0})

        return {'message': '操作成功'}
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')


@router.put('/templates/{id}', response_model=schemas.BaseApiOut)
async def edit_template(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    id: int,
    post: dict = Body(...),
):
    obj = OemModel.V2Oem.find(id)
    if obj is None:
        return schemas.BaseApiOut(code=1, message='找不到此信息')

    oem = OemModel.V2Oem.where('id', '!=', obj.id).where('domain', post.get('domain')).first()
    if oem is not None:
        return schemas.BaseApiOut(code=1, message='此域名已经存在')

    try:
        obj.domain = post.get('domain')
        obj.is_default = post.get('is_default')
        obj.domain = post.get('domain')
        obj.small_template = post.get('small_template')
        obj.ewm_template = post.get('ewm_template')
        obj.status = post.get('status')
        obj.save()

        if post.get('is_default') == 1:
            OemModel.V2Oem.where('id', '!=', obj.id).where('is_default', 1).update({'is_default': 0})

        return {'message': '操作成功'}
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')


@router.delete('/templates/{id}', response_model=schemas.BaseApiOut)
async def delete_template(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    id: int,
):
    obj = OemModel.V2Oem.find(id)
    if obj is None:
        return schemas.BaseApiOut(code=1, message='找不到此信息')

    # 启用的域名不能删除
    if obj.status == 1:
        return schemas.BaseApiOut(code=1, message='启用的域名不能删除')
    # 默认域名不能删除
    if obj.is_default == 1:
        return schemas.BaseApiOut(code=1, message='默认域名不能删除')

    try:
        obj.delete()

        return {'message': '操作成功'}
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')
